//
//  index.swift
//  uiKit-demo
//
//  Created by 陈澎 on 2025/1/8.
//
import UIKit
import Toast_Swift

struct PriceRageItem {
    var title: String
    var selected: Bool?
}

class GoodsListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    let filterTools = FilterToolsView()
    let priceRange = PriceRangeViewController()
    let storeTip = StoreTipViewController()
    let voucherGoodsApi = VoucherGoodsService(voucher_id: "RTKZNMOAOGCNB8P6")
    var keywords: String = ""
    let one_page_size: Int = 10
    var page_index: Int = 1
    var search_price: [String: String] = ["max": "", "min": ""]
    var goodsListView: UITableView?
    var voucherGoodsData: VoucherGoodsRes?
    var merchandiseLis: [VoucherGoodsRes.MercgabduseListItem] = []
    func getVoucherGoods() async {
        Task {
            do {
                let params: [String: Any] = [
                    "keywords": self.keywords,
                    "rebateVoucherId": "",
                    "one_page_size": self.one_page_size,
                    "only_camp": 0,
                    "page_index": self.page_index,
                    "search_price": self.search_price
                ]
                let resData = try await voucherGoodsApi.getVoucherGoods(params: params)
                if resData.errorCode != 0 {
                    print(resData.errorDesc)
                    self.view.makeToast(resData.errorDesc)
                    return
                }
                self.voucherGoodsData = resData.body
                self.merchandiseLis = resData.body.MerchandiseList ?? []
                DispatchQueue.main.async {
                    self.goodsListView!.reloadData()
                    self.goodsListView?.layoutIfNeeded()
                }
                
            }catch{
                print("请求失败")
            }
        }
    }
    
    func getVoucherInfo() {
        Task {
            do {
                let resData = try await voucherGoodsApi.getVoucherInfo(cart_type: 9)
                if resData.errorCode != 0 {
                    print(resData.errorDesc)
                    self.view.makeToast(resData.errorDesc)
                    return
                }
            }catch {
                print("请求失败")
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
         
        // self.getVoucherInfo()
        self.title = "网络请求"
        view.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
        Task {
            await self.getVoucherGoods()
            
            let topFixedView = UIView()
            topFixedView.translatesAutoresizingMaskIntoConstraints = false
            
            // 筛选排序
            filterTools.render(parentView: topFixedView)
            
            // 价格区间
            priceRange.render(parentView: topFixedView)
            
            view.addSubview(topFixedView)
            
            NSLayoutConstraint.activate([
                topFixedView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
                topFixedView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                topFixedView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
                topFixedView.heightAnchor.constraint(equalToConstant: ScaleBasedScene.getFinalSizeVal(87))
            ])
            
            let goodsListView = UITableView()
            goodsListView.allowsSelection = false
            goodsListView.register(GoodsItemViewCell.self, forCellReuseIdentifier: "cell")
            
//            goodsListView.backgroundColor = .red
            goodsListView.rowHeight = UITableView.automaticDimension
            goodsListView.translatesAutoresizingMaskIntoConstraints = false
            self.view.addSubview(goodsListView)
            goodsListView.delegate = self
            goodsListView.dataSource = self
            self.goodsListView = goodsListView
            
            NSLayoutConstraint.activate([
                goodsListView.topAnchor.constraint(equalTo: topFixedView.bottomAnchor),
                goodsListView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                goodsListView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
                goodsListView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            ])
            
        }
       
        // 添加约束
//        let topConstraint = label.topAnchor.constraint(equalTo: rootView.safeAreaLayoutGuide.topAnchor, constant: 20)
//        topConstraint.isActive = true
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.merchandiseLis.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! GoodsItemViewCell
        let curGoodsItem = self.merchandiseLis[indexPath.row]
        cell.configure(data: curGoodsItem)
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    internal func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if let voucherGoodsData = self.voucherGoodsData, let discountTip = voucherGoodsData.discountTip {
            storeTip.title = discountTip
            return storeTip.render(parentView: tableView)
        }
        return nil
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        print("section:\(tableView.sectionHeaderTopPadding)")
        return ScaleBasedScene.getFinalSizeVal(60)
    }
//    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> String? {
//        return "已经到底了"
//    }
}
